package com.wanwen.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wanwen.entity.Asker;
import com.wanwen.entity.AutoConfig;
import com.wanwen.entity.Student;
import com.wanwen.mapper.AskerMapper;
import com.wanwen.mapper.AutoConfigMapper;
import com.wanwen.mapper.StudentMapper;
import com.wanwen.utils.PoiUtils;
import com.wanwen.utils.Result;

/**
 * ClassName StuExcelController
 *
 * @Descroption
 * @Author lgl
 * @Date 2020/7/6 22:21
 **/
@RestController
@RequestMapping("excel")
public class ExcelController {
	@Autowired
	private StudentMapper studentMapper;
    @Autowired
    private AskerMapper askermapper;
	@Autowired
    private AutoConfigMapper autoConfigMapper;
	/**
	 * 模板导出
	 * 
	 * @param response
	 * @throws IOException
	 */
    @RequestMapping("/exportModel")
    public void exportModel(HttpServletResponse response,HttpSession session)
            throws IOException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String time = sdf.format(new Date());
        String downloadName = "学生信息"+time+".xls";
        response.setCharacterEncoding("UTF-8");// 设置响应的字符编码格式
        response.setContentType("application/vnd.ms-excel");// 指明响应文件为excel类型
        response.setHeader("Content-disposition", "attachment;filename="
                + new String(downloadName.getBytes("GB2312"), "ISO8859-1"));// 文件名编码处理，防止浏览器下载文件名乱码
        ServletOutputStream out = response.getOutputStream();
    	// 封装条件查询构造器
		QueryWrapper<Student> wrapper = new QueryWrapper<Student>();
		List<Student> list = studentMapper.selectList(wrapper);
		  try { 
			  PoiUtils p = new PoiUtils(); 
			  p.createExcel(list, Student.class,out); 
			 } catch (IOException e) { 
				 System.out.println(e.getMessage());
				e.printStackTrace(); 
			}
    }


	@RequestMapping(value = "/uploadStudent", name = "导入")
	public Object uploadTeacher(MultipartFile file, HttpSession session) {
		String name = file.getName();// form表单中参数名称
		String originalFilename = file.getOriginalFilename();// 得到上传文件的名称
		System.out.println("表单中文件参数名称 name=>" + name);
		System.out.println("上传的文件原始名称 originalfileName=>" + originalFilename);
		PoiUtils poiUtils = new PoiUtils();// Excel工具类
		List<Student> list = null;
		try {
			list = (List<Student>) poiUtils.parseExcel(Student.class, file.getInputStream(), originalFilename);
			AutoConfig autoConfig = autoConfigMapper.selectOne(null);
			int n =0;
			for (Student student : list) {
				n++;
				if(autoConfig.getIsAuto().equals("开启")) {
					QueryWrapper<Asker> askerWrapper = new QueryWrapper<Asker>()
							.eq("remark", "已签到").or().eq("remark", "未分配").or().eq("remark", "已分配");
					List<Asker> askerList = askermapper.selectList(askerWrapper );
					if(askerList.size()!=0) {
						//获取当天签到的权重最大的未分配的咨询师信息
						setChangeState(student);
						continue;
					}
				}
				studentMapper.insert(student);
			}
			for (Student t : list) {
				System.out.println(t);
			}
			//list.forEach(System.out::println);//jdk1.8新特性
			System.out.println("导入的数据长度：" + list.size() + ",插入的数据长度：" + n);
			// 批量插入
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (list != null) {
			return new Result("上传成功", true);
		} else {
			return new Result("上传失败", false);
		}
	}
	
	
	public Result setChangeState(Student stu) {
		//找当天已签到的未分配的权重最大的咨询师信息
		QueryWrapper<Asker> wrapper=new QueryWrapper<Asker>();
		wrapper.eq("remark", "已签到").or().eq("remark", "未分配")
		.orderByAsc("weight");
		List<Asker> allAsList=askermapper.selectList(wrapper);
		if(allAsList.size()>0) { // 有, asker ,把该咨询师人员的状态改为已分配
			Asker asker= allAsList.get(0);
			stu.setUid(asker.getUid());
			//把该咨询师人员的状态改为已分配
			asker.setRemark("已分配");
			QueryWrapper<Asker> wrapper2=new QueryWrapper<Asker>();
			wrapper2.eq("id", asker.getId());
			askermapper.update(asker, wrapper2);
			return new Result("", "", studentMapper.insert(stu)==1?true:false);
		}else {//没有,就更新当天签到的所有咨询师人员的状态为未分配
			QueryWrapper<Asker> wrapper3=new QueryWrapper<Asker>();
			wrapper3.eq("remark", "已分配");
			List<Asker> allAskerList=askermapper.selectList(wrapper3);
			  //获取当天签到的权重最大的未分配的咨询师信息
			for(Asker ars:allAskerList) {
				ars.setRemark("未分配");
				QueryWrapper<Asker> wrapper4=new QueryWrapper<Asker>();
				wrapper4.eq("id", ars.getId());
				askermapper.update(ars,wrapper4);
			}
			return 	setChangeState(stu);//递归调用;
	   }
	}
	
}
